package com.talkyun.ocean.impl;


import com.talkyun.ocean.model.Endpoint;
import com.talkyun.ocean.model.Provider;
import com.talkyun.ocean.model.Service;
import com.talkyun.ocean.service.RegistryManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LocalRegistryManager implements RegistryManager {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public Map<String, List<Provider>> api2Provider = new ConcurrentHashMap<String, List<Provider>>();
    public Map<String, List<Endpoint>> api2Endpoint = new ConcurrentHashMap<String, List<Endpoint>>();

    @Override
    public synchronized void registry(Provider provider, List<Service> services) {
        // logger.info("As service provider: {}", provider);
        for (Service info : services) {
            List<Provider> providers = api2Provider.get(info.getInterfaceName());
            if (providers == null) {
                providers = new ArrayList<Provider>();
                api2Provider.put(info.getInterfaceName(), providers);
            }

            // TODO provider 去重
            providers.add(provider);

            List<Endpoint> endpoints = api2Endpoint.get(info.getInterfaceName());
            if (endpoints == null) {
                endpoints = new ArrayList<Endpoint>();
                api2Endpoint.put(info.getInterfaceName(), endpoints);
            }
            Endpoint endpoint = new Endpoint(provider.getProtocol(), provider.getAddress(), provider.getPort(), info.getServiceMapping());
            endpoints.add(endpoint);

            logger.info("  -> registry {} to {} by {} ", info.getInterfaceName(), info.getServiceMapping(), endpoint);
        }
    }

    @Override
    public Service getServiceInfoByMapping(String serviceMapping) {
        return null;
    }

    @Override
    public Service getServiceInfoByInterface(String interfaceName) {
        return null;
    }

    @Override
    public List<Provider> listServiceProvider(String interfaceName) {
        List<Provider> list = api2Provider.get(interfaceName);
        return list == null ? Collections.emptyList() : list;
    }

    @Override
    public List<Endpoint> listEndpoint(String interfaceName) {
        List<Endpoint> list = api2Endpoint.get(interfaceName);
        return list == null ? Collections.emptyList() : list;
    }
}